<?php
namespace app\shop\controller;
use app\AdminRest;
use app\helppay\model\Helppay;
use app\material\model\Folder;
use app\member\model\Goods;
use app\member\model\Member;
use app\publics\model\TmplConfig;
use app\shop\model\AdminCompany;
use app\shop\model\Express;
use app\shop\model\ExpressOrder;
use app\shop\model\IndexCouponRecord;
use app\shop\model\Printer;
use longbingcore\wxcore\WxSetting;
use longbingcore\wxcore\WxTmpl;
use think\App;
use think\facade\Cache;
use think\facade\Db;
use think\Request;
use app\shop\model\AdminShopOrder as ShopOderModel;
use app\shop\model\AdminShopOrderRefund;
use app\shop\model\IndexCardCount;
use app\shop\model\AdminSellingWater;
use app\shop\model\AdminSellingProfit;
use app\shop\model\IndexUser;


class AdminShopOrder extends AdminRest
{

    protected $model;
    protected $refund_model;
    protected $count_model;
    protected $water_model;
    protected $profit_model;
    protected $user_model;
    public function __construct(App $app) {
        parent::__construct($app);
        $this->model        = new ShopOderModel();

        $this->count_model  = new IndexCardCount();

        $this->refund_model = new AdminShopOrderRefund();

        $this->water_model  = new AdminSellingWater();

        $this->profit_model = new AdminSellingProfit();

        $this->user_model   = new IndexUser();

        $this->company      = new AdminCompany();
        //检测订单
        $this->model->checkOrder($this->_uniacid,$this->_config);
    }






    /**
     * User: chenniang
     * Date: 2019-09-11 18:54
     * @return \think\Response
     * descption:获取订单列表
     */
    public function orderList(){

//        $a = longbingCreateWxCode($this->_uniacid,[],'pages/index/index?id=1',1);
//
//        dump($a);exit;

//        dump(openssl_get_cert_locations());exit;


//        $a = new Printer();
//
//        $b = $a->printer(191,1);
//
//        dump($b);exit;

        $page = $this->_input['limit'];

        $name = $this->_input['name'];

        if(!empty($this->_input['order_status'])){

            $dis = $this->orderStatus($this->_input['order_status']);
        }
        if(!empty($this->_input['transaction_id'])){
            $dis[] = ['a.transaction_id','like','%'.trim($this->_input['transaction_id'])."%"];
        }
        if(!empty($this->_input['order_code'])){
            $dis[] = ['a.out_trade_no','like',"%".trim($this->_input['order_code'])."%"];
        }
        if(!empty($name)){
            $dis[] = ['b.name','like',"%".$name."%"];
        }
        if(!empty($this->_input['phone'])){
            $dis[] = ['a.phone','like',"%".$this->_input['phone']."%"];
        }

        //自提
        if(!empty($this->_input['is_self'])&&$this->_input['is_self']==1){

            $dis[] = ['a.address_id','=',-1];
        }
        //快递
        if(!empty($this->_input['is_self'])&&$this->_input['is_self']==2){

            $dis[] = ['a.address_id','>',0];
        }

        /**
         * 开始时间&结束时间 查询
         * @start_time 格式 YY-mm-dd . 00:00:00
         * @end_time 格式 YY-mm-dd . 23:59:59
         */
        if(!empty($this->_input['start_time'])){
            $start_time = strtotime($this->_input['start_time']. ' 00:00:00');
            $dis[] = ['a.create_time','>=',$start_time];
        }
        if(!empty($this->_input['end_time'])){
            $end_time = strtotime($this->_input['end_time']. ' 23:59:59');
            $dis[] = ['a.create_time','<=',$end_time];
        }

        /**
         * 根据公司部门筛选
         */
        if(!empty($this->_input['company'])){

            $company = $this->_input['company'];

            $cpy_ids = $this->company->companyLow($company);

            array_unshift($cpy_ids,$company);

            $dis[] = ['c.company_id','in',$cpy_ids];
        }

        $dis[]     = ['a.uniacid','=',$this->_uniacid];
        $data = $this->model->orderList($dis,$page);

        if(!empty($data['data'])){
            foreach ($data['data'] as &$v){
                $v['goods_info_text'] = $this->goodsText($v['goods_text']);
            }
        }
        return $this->success($data);
    }

    /**
     * 获取商品拼接
     */

    public function goodsText($data){
        $names = '';
        if(is_array($data)){
            foreach ($data as $value){
                $names .=  $value[ 'name' ] . ': ' . $value[ 'content' ] . '，数量：' . $value[ 'number' ].';';
            }
        }
        return $names;
    }

    /**
     *
     * 订单状态
     */

    public function orderStatus($type){
        switch ( $type ) {
            //  1=>待付款
            case 1:
                $where[] = [ 'a.pay_status','=',0 ];
                $where[] = [ 'a.order_status','=',0 ];
                break;
            //  2=>待发货
            case 2:
                $where[] = [ 'a.pay_status','=',1 ];
                $where[] = [ 'a.order_status','=',0 ];
                break;
            //  3=>待收货
            case 3:
                $where[] = [ 'a.pay_status','=',1 ];
                $where[] = [ 'a.order_status','=',2 ];
                break;
            //  4=>已完成
            case 4:
                $where[] = [ 'a.pay_status','=',1 ];
                $where[] = [ 'a.order_status','>',2 ];
                break;
            //  5=>已取消
            case 5:
                $where[] = [ 'a.order_status','=',1 ];
                break;
            //  0=>全部订单
            default:
        }
        return $where;
    }

    /**
     * @author chenniang
     * @DataTime: 2021-04-12 17:29
     * @功能说明:发货
     */
    public function orderSend(){

        $dis['id'] = $this->_input['id'];

        $order     = $this->model->orderInfo($dis);

        if(empty($order)){

            return $this->error('订单未找到');
        }

        if($order['refund_status']!=0&&$order['refund_status']!=3){

            return $this->error('status is error');
        }

        $this->_input['order_status'] = 2;

        if(!empty($this->_input['send'])){
            //新版物流通知 添加物流信息
            $express_model = new ExpressOrder();

            $express_model->expressAdd($order['id'],$this->_uniacid,$this->_input['send']);

            unset($this->_input['send']);
        }


        $res = $this->model->orderUpdate($dis,$this->_input);

        if($res){
            $insertData = array(
                'user_id' => $order['user_id'],
                'to_uid'  => $order['to_uid'],
                'sign'    => 'view',
                'type'    => 19,
                'uniacid' => $this->_uniacid,
                'target'  => $order['id']
            );
            $insert_id = $this->count_model->countAdd($insertData);
            $push_data = array(
                'action'  => 'longbingSendWxServiceNotice',
                'event'   => 'longbingSendWxServiceNotice',
                'count_id'=> $insert_id
            );
            publisher(json_encode($push_data ,true));

            $order     = $this->model->orderInfo($dis);

            $res = $this->model->sendOrderService($order);
        }
        return $this->success($res);
    }
    /**
     * 获取订单详情
     *
     */
    public function orderInfo(){

        $dis[]= ['id','=',$this->_input['id']];

        $data = $this->model->orderInfo($dis);

        if(!empty($data)){

            $data['should_pay'] = round($data['price'] + $data['freight'],2);

            $data['coupon_pay'] = round($data['should_pay'] - $data['total_price'],2);
        }

        $data['goods_info_text'] = !empty($data['goods_text'])?$this->goodsText($data['goods_text']):'';

        $help_model = new Helppay();
        //代付信息
        $data['help_list'] = $help_model->helpList($data['id']);

        return $this->success($data);
    }
    /**
     * User: chenniang
     * Date: 2019-09-11 10:21
     * @return void
     * descption:提货
     */
    public function selfOrder(){

        $input = $this->_input;

        $order = $this->model->orderInfo(['id'=>$input['id']]);

        if(empty($order)){

            return $this->error('no data');
        }
        if($order['order_status']!=0){

            return $this->error('订单状态错误');
        }

        if($order['refund_status']!=0){

            return $this->error('订单已申请退款');

        }
        Db::startTrans();

        $res = $this->model->orderUpdate(['id'=>$input['id']],['order_status'=>3,'hx_time'=>time()]);

        if($res){
            //会员模型
            $member_model = new Member();
            //结算会员的商品的权益
            $member_model->updateMember($order);

            $this->profitUpdate($order);

            $insertData = array(
                'user_id' => $order['user_id'],
                'to_uid'  => $order['to_uid'],
                'sign'    => 'view',
                'type'    => 20,
                'uniacid' => $this->_uniacid,
                'target'  => $order['id'],
            );
            $insert_id = $this->count_model->countAdd($insertData);
            $push_data = array(
                'action'  => 'longbingSendWxServiceNotice',
                'event'   => 'longbingSendWxServiceNotice',
                'count_id'=> $insert_id
            );
            publisher(json_encode($push_data ,true));


        }

        Db::commit();

        return $this->success($res);
    }




    /**
     * User: chenniang
     * Date: 2019-09-11 10:35
     * @param $order
     * @return bool
     * descption:修改佣金
     */
    public function profitUpdate($order){
        $list = $this->water_model->where(['order_id' => $order['id'], 'waiting' => 1])->select();

        if(!empty($list)){

            foreach ($list as $index => $item) {

                $money = $item['price'] * $item['extract'] / 100;

                if($item['selling_type']==1){

                    $money = $item[ 'extract_cash' ];
                }
                $money = sprintf("%.2f", $money);

                $profit= $this->profit_model->profitInfo(['user_id' => $item['user_id']]);

                if ($profit) {

                    if ($profit['waiting'] >= $money) {
                        $waiting      = $profit['waiting'] - $money;
                        $total_profit = $profit['total_profit'] + $money;
                        $profit_money = $profit['profit'] + $money;
                        $waiting      = sprintf("%.2f", $waiting);
                    } else {
                        $waiting      = 0;
                        $money        = $profit['waiting'];
                        $total_profit = $profit['total_profit'] + $profit['waiting'];
                        $profit_money = $profit['profit'] + $profit['waiting'];
                    }
                    $total_profit = sprintf("%.2f", $total_profit);

                    $profit_money = sprintf("%.2f", $profit_money);

                    $this->profit_model->profitUpdate(['id' => $profit['id']],['waiting' => $waiting, 'total_profit' => $total_profit, 'profit' => $profit_money]);

                    $this->user_model->userUpdate(['id' => $item['source_id']],['create_money'=>Db::raw("create_money+$money")]);
                }
            }
        }

        $res  = $this->water_model->waterUpdate(['order_id' => $order['id'], 'waiting' => 1],['waiting' => 2]);

        return true;
    }
    /**
     * User: chenniang
     * Date: 2019-09-11 19:22
     * @return void
     * descption:按部门|员工更新订单
     */
    public function refreshOrder(){
        $dis[] = ['uniacid'   ,'=',$this->_uniacid];
        $dis[] = ['company_id','=',0];
        $dis[] = ['pay_status','=',1];
        $dis[] = ['to_uid'    ,'<>',0];
        $order = $this->model->where($dis)->select()->toArray();
        if(!empty($order)){
            foreach ($order as $value){
                $staff = Db::name('longbing_card_user_info')->where([ 'fans_id' => $value[ 'to_uid' ]])->field('company_id')->find();
                if(!empty($staff['company_id'])){
                    $this->model->orderUpdate(['id'=>$value['id'],'company_id'=>0],['company_id'=>$staff['company_id']]);
                }
            }
        }
        return $this->success(true);
    }
    /**
     * User: chenniang
     * Date: 2019-09-12 18:37
     * @return bool
     * descption:检查订单
     */
    public function checkOrder(){

        $this->model->checkOrder($this->_uniacid,$this->_config);

        return true;
    }
    /**
     * User: chenniang
     * Date: 2019-09-12 14:43
     * @return void
     * descption: 检查超时订单
     */
    public function checkOrderTime(){
        $order_overtime  = !empty($this->_config['order_overtime'])?$this->_config['order_overtime']:1800;
        $order_overtime  = time() - $order_overtime;
        $order_dis[] = ['uniacid','=',$this->_uniacid];
        $order_dis[] = ['pay_status','=',0];
        $order_dis[] = ['order_status','<>',1];
        $order_dis[] = ['refund_status','=',0];
        $order_dis[] = ['create_time','<',$order_overtime];
        $order       = Db::name('longbing_card_shop_order')->where($order_dis)->field('id,record_id,collage_id,user_id,type')->select();
        if(!empty($order)){
            foreach ($order as $v){
                $this->model->orderUpdate(['id'=>$v['id']],['order_status' => 1]); //取消超时订单
                if(!empty($v['record_id'])){
                    Db::name('longbing_card_coupon_record')->where(['id'=>$v['record_id']])->update(['status'=>1,'update_time'=>time()]);//恢复优惠券状态
                }
                if($v['type']==1){ //拼团
                    $user = Db::name('longbing_card_shop_collage_list')->where(['id'=>$v['collage_id']])->value('user_id');
                    Db::name('longbing_card_shop_user_collage')->where(['collage_id'=>$v['collage_id'],'user_id'=>$v['user_id']])->update(['collage_status'=>4]);
                    if($v['user_id']==$user){
                        Db::name('longbing_card_shop_collage_list')->where(['id'=>$v['collage_id']])->update(['status'=>4]);
                    }else{
                        Db::name('longbing_card_shop_collage_list')->where(['id'=>$v['collage_id']])->update(['left_number'=>Db::raw('left_number+1')]);
                    }
                }
            }
        }
        return true;
    }
    /**
     * User: chenniang
     * Date: 2019-09-12 18:28
     * @return bool
     * descption:取消超时拼团
     */
    public function checkCollageTime(){
        $collage_overtime = !empty($this->_config['collage_overtime'])?$this->_config['collage_overtime']:3600;
        $collage_overtime = time() - $collage_overtime;
        $collage_status[] = ['collage_status','=',1];
        $collage_status[] = ['uniacid','=',$this->_uniacid];
        $collage_status[] = ['create_time','<',$collage_overtime];
        $collage = Db::name('longbing_card_shop_collage_list')->where($collage_status)->select();
        Db::name('longbing_card_shop_collage_list')->where($collage_status)->update(['collage_status'=>4]);
        if(!empty($collage)){
            foreach ($collage as $value){
                $order = Db::name('longbing_card_shop_order')->where(['collage_id'=>$value['id'],'type'=>1])->field('id,order_status,pay_status')->select();
                Db::name('longbing_card_shop_user_collage')->where(['collage_id' => $value['id']])->update(['collage_status' => 4]);
                if(!empty($order)){
                    foreach ($order as $v){
                        $this->model->orderUpdate(['id'=>$v['id']],['order_status'=>1]);
                        if($v['pay_status']==1){
                            $this->water_model->refundWater(['order_id' => $v['id'], 'waiting'=>1]);
                        }
                    }
                }
            }
        }
        return true;
    }
    /**
     * User: chenniang
     * Date: 2019-09-12 18:28
     * @return bool
     * descption:自动收货
     */
    public function checkSendTime(){
        $receiving = empty($this->_config['receiving'])||$this->_config['receiving']<5?5:$this->_config['receiving'];
        $beginTime = time()-$receiving*86400;
        $dis[] = ['uniacid'      ,'=',$this->_uniacid];
        $dis[] = ['pay_status'   ,'=',1];
        $dis[] = ['order_status' ,'=',2];
        $dis[] = ['refund_status','=',0];
        $dis[] = ['update_time'  ,'<',$beginTime];
        $list  = Db::name('longbing_card_shop_order')->where($dis)->field('id')->select();
        if (!empty($list)) {
            foreach ( $list as $index => $item ) {

                $this->model->orderUpdate(['id'=>$item['id']],['order_status'=>3,'hx_time'=>time()]);

                $this->profitUpdate($item);
                //会员模型
                $member_model = new Member();
                //结算会员的商品的权益
                $member_model->updateMember($item);
            }
        }
        return true;
    }


    /**
     * @author chenniang
     * @DataTime: 2021-04-14 15:16
     * @功能说明:快递信息
     */
    public function orderExpressInfo(){

        $input = $this->_param;

        $update= !empty($input['update'])?1:0;

        $express_model = new ExpressOrder();

        $order = $express_model->expressInfo($input['order_id'],$this->_uniacid,$update);

        return $this->success($order);

    }


    /**
     * @author chenniang
     * @DataTime: 2021-04-15 16:06
     * @功能说明:修改快递信息
     */
    public function expressUpdate(){

        $input = $this->_input;
        //新版物流通知 添加物流信息
        $express_model = new ExpressOrder();

        $res = $express_model->expressAdd($input['order_id'],$this->_uniacid,$input['send']);

        $update = [

            'courier_number' => $input['courier_number'],

            'express_company'=> $input['express_company']
        ];

        $this->model->orderUpdate(['id'=>$input['order_id']],$update);

        $key = 'express_order'.$input['order_id'];
        //清除缓存
        delCache($key,$this->_uniacid);


        return $this->success($res);


    }




}
